package hamaster.jpbc.pbc;

import it.unisa.dia.gas.jpbc.Element;

import java.util.Properties;

public class CipherText implements Propertiable {

	static String CIPHERU_POSTFIX = "cu";
	static String CIPHERV_POSTFIX = "cv";
	static String CIPHERW_POSTFIX = "cw";
	static String PLAIN_LENGTH_POSTFIX = "length";

	private Element u;
	private Element v;
	private Element w;
	private int length;

	public CipherText() {
	}

	public CipherText(Properties properties, String prefix) {
		setFromProperties(properties, prefix);
	}

	public Element getU() {
		return u;
	}

	public void setU(Element u) {
		this.u = u;
	}

	public Element getV() {
		return v;
	}

	public void setV(Element v) {
		this.v = v;
	}

	public Element getW() {
		return w;
	}

	public void setW(Element w) {
		this.w = w;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public int getLength() {
		return length;
	}

	@Override
	public boolean setFromProperties(Properties properties, String prefix) {
		String uk = CIPHERU_POSTFIX;
		String vk = CIPHERV_POSTFIX;
		String wk = CIPHERW_POSTFIX;
		String lk = PLAIN_LENGTH_POSTFIX;
		if (prefix != null && prefix.length() > 0) {
			uk = prefix + "." + CIPHERU_POSTFIX;
			vk = prefix + "." + CIPHERV_POSTFIX;
			wk = prefix + "." + CIPHERW_POSTFIX;
			lk = prefix + "." + PLAIN_LENGTH_POSTFIX;
		}
		String us = properties.getProperty(uk);
		String vs = properties.getProperty(vk);
		String ws = properties.getProperty(wk);
		String ls = properties.getProperty(lk);
		if (us == null || vs == null || ws == null || ls == null)
			return false;
		PBC pbc = PBC.instance();
		u = pbc.getPairing().getG1().newElement();
		v = pbc.getPairing().getGT().newElement();
		w = pbc.getPairing().getGT().newElement();
		u.setFromBytes(PBCDriver.unhex(us));
		v.setFromBytes(PBCDriver.unhex(vs));
		w.setFromBytes(PBCDriver.unhex(ws));
		try {
			length = Integer.parseInt(ls);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	@Override
	public Properties toProperties(String prefix) {
		String uk = CIPHERU_POSTFIX;
		String vk = CIPHERV_POSTFIX;
		String wk = CIPHERW_POSTFIX;
		String lk = PLAIN_LENGTH_POSTFIX;
		if (prefix != null && prefix.length() > 0) {
			uk = prefix + "." + CIPHERU_POSTFIX;
			vk = prefix + "." + CIPHERV_POSTFIX;
			wk = prefix + "." + CIPHERW_POSTFIX;
			lk = prefix + "." + PLAIN_LENGTH_POSTFIX;
		}
		Properties p = new Properties();
		p.setProperty(uk, PBCDriver.hex(u.toBytes()));
		p.setProperty(vk, PBCDriver.hex(v.toBytes()));
		p.setProperty(wk, PBCDriver.hex(w.toBytes()));
		p.setProperty(lk, length + "");
		return p;
	}

	@Override
	public String toString() {
		return "[CipherText]\nu=" + u + "\nv=" + v + "\nw=" + w + "\n";
	}
}
